# Copyright (c) 2005,2006,2007 Dynamic Solutions Inc. (support@dynamic-solutions.com)
#
# This file is part of DataZoomer.
#
# DataZoomer is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# DataZoomer is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

"""Launches the DataZoomer system"""

import sys, os, cgi
from types import ListType

class dzCgiWebVars:

    def __init__(self,fields):

        # switch to binary mode on windows systems
        try:
            import msvcrt,os
            msvcrt.setmode( 0, os.O_BINARY ) # stdin  = 0
            msvcrt.setmode( 1, os.O_BINARY ) # stdout = 1
        except ImportError:
            pass

        f = fields
        for key in f.keys():
            if not self.__dict__.has_key(key):
                if type(f[key])==ListType:
                    # selection inputs have a list of MiniFieldStorage instances
                    self.__dict__[key] = ','.join(['"%s"' % item.value for item in f[key]])
                elif not f[key].filename:
                    # if button pressed, SaveBut.x=12 then add a variable SaveBut=1
                    if key[-2:]=='.x': self.__dict__[key[:-2]] = '1'
                    self.__dict__[key] = f[key].value
                else:
                    self.__dict__[key] = f[key]

    def __repr__(self):
        return 'webvars!'

    def __str__(self):
        return repr(self.__dict__)

    def __getattr__(self,name):
        return ''

    def _clear(self):
        self.__dict__ = {}

def dump(msg):
    sys.stdout.write('Content-type: text/html\nCache-Control: no-cache\r\n\n\n%s'%str(msg).replace('<','&lt;').replace('>','&gt;'))

def run_as_cgi(launcher=None,config_file=None):
    import dzsystem
    dzsystem.config_file_name = config_file
    dzsystem.site_launcher = launcher

    import dzmanager
    if os.environ.get('REQUEST_METHOD','GET').upper() in ['GET']:
        request = dzCgiWebVars(cgi.FieldStorage(environ=os.environ,keep_blank_values=1))
    else:
        request = dzCgiWebVars(cgi.FieldStorage(fp=sys.stdin, environ=os.environ, keep_blank_values=1))
    manager = dzmanager.Manager()

    # Call the main datazoomer module to respond to the request
    doc = manager.respond(request)

    del request
    sys.stdout.write(doc)
    manager.close()


